package fr.pentalog.ctc.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import fr.pentalog.ctc.dao.BaseDao;


/**
 * @author Danut Chindris
 * @since September 12, 2013
 */

@Repository
public class BaseDaoImpl implements BaseDao {

	@Resource
	private SessionFactory sessionFactory;

	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	protected Session openSession() {
		return sessionFactory.openSession();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> getObjectByProperty(Class<T> type, String propertyName, String propertyValue) {
		String hql = " from " + type.getName().substring(type.getName().lastIndexOf('.') + 1) + " where " + propertyName + " = :givenValue ";
		Query query = this.getCurrentSession().createQuery(hql);
		query.setString("givenValue", propertyValue);
		return query.list();
	}

	@SuppressWarnings("unchecked")
	public <T> T getObjectById(Class<T> type, Long id) {
		return (T)this.getCurrentSession().get(type, id);
	}
}
